package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.contant.ActivityConstant;
import com.itjin.mapper.CampusActivityMapper;
import com.itjin.mapper.UserMapper;
import com.itjin.model.domain.dto.ActivityCreateDTO;
import com.itjin.model.domain.dto.ActivityEditDTO;
import com.itjin.model.domain.dto.ActivityJoinDTO;
import com.itjin.model.domain.entity.CampusActivity;
import com.itjin.model.domain.entity.User;
import com.itjin.model.domain.vo.ActivityDetailVO;
import com.itjin.model.domain.vo.ActivityListVO;
import com.itjin.model.result.PageResult;
import com.itjin.service.CampusActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 校园活动服务实现类
 */
@Slf4j
@Service
public class CampusActivityServiceImpl implements CampusActivityService {

    @Autowired
    private CampusActivityMapper campusActivityMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityDetailVO createActivity(ActivityCreateDTO activityCreateDTO) {
        try {
            log.info("创建活动，举办人ID：{}，活动名称：{}", activityCreateDTO.getOrganizerId(), activityCreateDTO.getActivityName());
            
            // 参数校验
            validateActivityCreateDTO(activityCreateDTO);
            
            CampusActivity activity = new CampusActivity();
            BeanUtils.copyProperties(activityCreateDTO, activity);
            
            // 设置默认值
            if (activity.getActivityType() == null) {
                activity.setActivityType(ActivityConstant.DEFAULT_ACTIVITY_TYPE);
            }
            if (activity.getMaxParticipants() == null) {
                activity.setMaxParticipants(ActivityConstant.DEFAULT_MAX_PARTICIPANTS);
            }
            activity.setActivityStatus(ActivityConstant.DEFAULT_ACTIVITY_STATUS);
            activity.setCurrentParticipants(0);
            activity.setParticipantIds(new ArrayList<>());
            activity.setCreateTime(LocalDateTime.now());
            activity.setUpdateTime(LocalDateTime.now());
            activity.setIsDelete(0);
            
            int result = campusActivityMapper.insert(activity);
            if (result <= 0) {
                throw new RuntimeException("创建活动失败");
            }
            
            log.info("成功创建活动，活动ID：{}", activity.getId());
            return convertToDetailVO(activity, null);
            
        } catch (Exception e) {
            log.error("创建活动失败：", e);
            throw new RuntimeException("创建活动失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityDetailVO editActivity(ActivityEditDTO activityEditDTO) {
        try {
            log.info("编辑活动，活动ID：{}", activityEditDTO.getId());
            
            // 参数校验
            validateActivityEditDTO(activityEditDTO);
            
            // 检查活动是否存在
            CampusActivity existingActivity = campusActivityMapper.selectById(activityEditDTO.getId());
            if (existingActivity == null) {
                throw new RuntimeException("活动不存在");
            }
            
            CampusActivity activity = new CampusActivity();
            BeanUtils.copyProperties(activityEditDTO, activity);
            activity.setUpdateTime(LocalDateTime.now());
            
            int result = campusActivityMapper.updateById(activity);
            if (result <= 0) {
                throw new RuntimeException("编辑活动失败");
            }
            
            log.info("成功编辑活动，活动ID：{}", activity.getId());
            
            // 返回更新后的活动详情
            CampusActivity updatedActivity = campusActivityMapper.selectById(activity.getId());
            return convertToDetailVO(updatedActivity, null);
            
        } catch (Exception e) {
            log.error("编辑活动失败：", e);
            throw new RuntimeException("编辑活动失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteActivity(Integer activityId, Integer operatorId) {
        try {
            log.info("删除活动，活动ID：{}，操作者ID：{}", activityId, operatorId);
            
            if (activityId == null) {
                throw new RuntimeException("活动ID不能为空");
            }
            
            CampusActivity activity = campusActivityMapper.selectById(activityId);
            if (activity == null) {
                throw new RuntimeException("活动不存在");
            }
            
            // 检查权限：只有举办人可以删除活动
            if (!activity.getOrganizerId().equals(operatorId)) {
                throw new RuntimeException("只有举办人可以删除活动");
            }
            
            // 逻辑删除
            CampusActivity updateActivity = new CampusActivity();
            updateActivity.setId(activityId);
            updateActivity.setIsDelete(1);
            updateActivity.setUpdateTime(LocalDateTime.now());
            
            int result = campusActivityMapper.updateById(updateActivity);
            boolean success = result > 0;
            
            if (success) {
                log.info("成功删除活动，活动ID：{}", activityId);
            }
            
            return success;
            
        } catch (Exception e) {
            log.error("删除活动失败：", e);
            throw new RuntimeException("删除活动失败：" + e.getMessage());
        }
    }

    @Override
    public ActivityDetailVO getActivityDetail(Integer activityId, Integer userId) {
        try {
            log.info("获取活动详情，活动ID：{}，用户ID：{}", activityId, userId);
            
            if (activityId == null) {
                throw new RuntimeException("活动ID不能为空");
            }
            
            CampusActivity activity = campusActivityMapper.selectById(activityId);
            if (activity == null) {
                throw new RuntimeException("活动不存在");
            }
            
            return convertToDetailVO(activity, userId);
            
        } catch (Exception e) {
            log.error("获取活动详情失败：", e);
            throw new RuntimeException("获取活动详情失败：" + e.getMessage());
        }
    }

    @Override
    public PageResult<ActivityListVO> getActivityList(Integer activityType, Integer activityStatus, 
                                                    Long current, Long size) {
        try {
            log.info("分页查询活动列表，类型：{}，状态：{}，页码：{}，大小：{}", 
                    activityType, activityStatus, current, size);
            
            QueryWrapper<CampusActivity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("isDelete", 0);
            
            if (activityType != null) {
                queryWrapper.eq("activityType", activityType);
            }
            if (activityStatus != null) {
                queryWrapper.eq("activityStatus", activityStatus);
            }
            
            queryWrapper.orderByDesc("createTime");
            
            Page<CampusActivity> page = new Page<>(current, size);
            Page<CampusActivity> result = campusActivityMapper.selectPage(page, queryWrapper);
            
            List<ActivityListVO> records = result.getRecords().stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
            PageResult<ActivityListVO> pageResult = new PageResult<>();
            pageResult.setCode(200);
            pageResult.setCurrentPage(Math.toIntExact(result.getCurrent()));
            pageResult.setPageSize(Math.toIntExact(result.getSize()));
            pageResult.setTotal(result.getTotal());
            pageResult.setTotalPages(Math.toIntExact(result.getPages()));
            pageResult.setData(records);
            
            return pageResult;
            
        } catch (Exception e) {
            log.error("分页查询活动列表失败：", e);
            throw new RuntimeException("查询活动列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<ActivityListVO> getMyCreatedActivities(Integer organizerId) {
        try {
            log.info("获取用户创建的活动列表，举办人ID：{}", organizerId);
            
            if (organizerId == null) {
                throw new RuntimeException("举办人ID不能为空");
            }
            
            List<CampusActivity> activities = campusActivityMapper.findByOrganizerId(organizerId);
            
            return activities.stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取用户创建的活动列表失败：", e);
            throw new RuntimeException("获取用户创建的活动列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<ActivityListVO> getMyJoinedActivities(Integer userId) {
        try {
            log.info("获取用户参与的活动列表，用户ID：{}", userId);
            
            if (userId == null) {
                throw new RuntimeException("用户ID不能为空");
            }
            
            List<CampusActivity> activities = campusActivityMapper.findByParticipantId(userId);
            
            return activities.stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取用户参与的活动列表失败：", e);
            throw new RuntimeException("获取用户参与的活动列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean joinActivity(ActivityJoinDTO activityJoinDTO) {
        try {
            log.info("用户参加活动，活动ID：{}，用户ID：{}", activityJoinDTO.getActivityId(), activityJoinDTO.getUserId());
            
            // 参数校验
            if (activityJoinDTO.getActivityId() == null) {
                throw new RuntimeException("活动ID不能为空");
            }
            if (activityJoinDTO.getUserId() == null) {
                throw new RuntimeException("用户ID不能为空");
            }
            
            CampusActivity activity = campusActivityMapper.selectById(activityJoinDTO.getActivityId());
            if (activity == null) {
                throw new RuntimeException("活动不存在");
            }
            
            // 检查活动状态
            if (!ActivityConstant.ActivityStatus.REGISTRATION.getCode().equals(activity.getActivityStatus())) {
                throw new RuntimeException("活动不在报名状态，无法参加");
            }
            
            // 检查报名截止时间
            if (activity.getRegistrationDeadline() != null && 
                LocalDateTime.now().isAfter(activity.getRegistrationDeadline())) {
                throw new RuntimeException("报名时间已截止");
            }
            
            // 检查是否已经参加
            String userIdStr = activityJoinDTO.getUserId().toString();
            if (activity.getParticipantIds() != null && activity.getParticipantIds().contains(userIdStr)) {
                throw new RuntimeException("您已经参加了此活动");
            }
            
            // 检查人数限制
            if (activity.getMaxParticipants() > 0 && 
                activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
                throw new RuntimeException("活动人数已满，无法参加");
            }
            
            // 添加参与者
            List<String> participantIds = activity.getParticipantIds();
            if (participantIds == null) {
                participantIds = new ArrayList<>();
            }
            participantIds.add(userIdStr);
            
            // 更新活动信息
            CampusActivity updateActivity = new CampusActivity();
            updateActivity.setId(activity.getId());
            updateActivity.setParticipantIds(participantIds);
            updateActivity.setCurrentParticipants(participantIds.size());
            updateActivity.setUpdateTime(LocalDateTime.now());
            
            int result = campusActivityMapper.updateById(updateActivity);
            boolean success = result > 0;
            
            if (success) {
                log.info("用户成功参加活动，活动ID：{}，用户ID：{}", activityJoinDTO.getActivityId(), activityJoinDTO.getUserId());
            }
            
            return success;
            
        } catch (Exception e) {
            log.error("参加活动失败：", e);
            throw new RuntimeException("参加活动失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitActivity(Integer activityId, Integer userId) {
        try {
            log.info("用户退出活动，活动ID：{}，用户ID：{}", activityId, userId);
            
            if (activityId == null) {
                throw new RuntimeException("活动ID不能为空");
            }
            if (userId == null) {
                throw new RuntimeException("用户ID不能为空");
            }
            
            CampusActivity activity = campusActivityMapper.selectById(activityId);
            if (activity == null) {
                throw new RuntimeException("活动不存在");
            }
            
            // 检查是否已参加
            String userIdStr = userId.toString();
            if (activity.getParticipantIds() == null || !activity.getParticipantIds().contains(userIdStr)) {
                throw new RuntimeException("您未参加此活动");
            }
            
            // 移除参与者
            List<String> participantIds = new ArrayList<>(activity.getParticipantIds());
            participantIds.remove(userIdStr);
            
            // 更新活动信息
            CampusActivity updateActivity = new CampusActivity();
            updateActivity.setId(activityId);
            updateActivity.setParticipantIds(participantIds);
            updateActivity.setCurrentParticipants(participantIds.size());
            updateActivity.setUpdateTime(LocalDateTime.now());
            
            int result = campusActivityMapper.updateById(updateActivity);
            boolean success = result > 0;
            
            if (success) {
                log.info("用户成功退出活动，活动ID：{}，用户ID：{}", activityId, userId);
            }
            
            return success;
            
        } catch (Exception e) {
            log.error("退出活动失败：", e);
            throw new RuntimeException("退出活动失败：" + e.getMessage());
        }
    }

    @Override
    public List<ActivityListVO> getPopularActivities(Integer limit) {
        try {
            log.info("获取热门活动列表，限制数量：{}", limit);
            
            if (limit == null || limit <= 0) {
                limit = 10;
            }
            
            List<CampusActivity> activities = campusActivityMapper.findPopularActivities(limit);
            
            return activities.stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取热门活动列表失败：", e);
            throw new RuntimeException("获取热门活动列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<ActivityListVO> getUpcomingActivities() {
        try {
            log.info("获取即将开始的活动列表");
            
            List<CampusActivity> activities = campusActivityMapper.findUpcomingActivities();
            
            return activities.stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取即将开始的活动列表失败：", e);
            throw new RuntimeException("获取即将开始的活动列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<ActivityListVO> getActivitiesByType(Integer activityType, Integer limit) {
        try {
            log.info("根据类型获取活动列表，类型：{}，限制数量：{}", activityType, limit);
            
            if (activityType == null) {
                throw new RuntimeException("活动类型不能为空");
            }
            if (limit == null || limit <= 0) {
                limit = 10;
            }
            
            List<CampusActivity> activities = campusActivityMapper.findByActivityType(activityType, limit);
            
            return activities.stream()
                    .map(this::convertToListVO)
                    .collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("根据类型获取活动列表失败：", e);
            throw new RuntimeException("根据类型获取活动列表失败：" + e.getMessage());
        }
    }

    /**
     * 将Activity实体转换为ActivityDetailVO
     */
    private ActivityDetailVO convertToDetailVO(CampusActivity activity, Integer userId) {
        ActivityDetailVO vo = new ActivityDetailVO();
        BeanUtils.copyProperties(activity, vo);
        
        // 设置描述信息
        vo.setActivityTypeDesc(ActivityConstant.ActivityType.getDescByCode(activity.getActivityType()));
        vo.setActivityStatusDesc(ActivityConstant.ActivityStatus.getDescByCode(activity.getActivityStatus()));
        
        // 获取举办人姓名
        if (activity.getOrganizerId() != null) {
            User organizer = userMapper.selectById(activity.getOrganizerId());
            if (organizer != null) {
                vo.setOrganizerName(organizer.getUsername());
            }
        }
        
        // 判断是否可以报名
        vo.setCanRegister(canRegisterActivity(activity));
        
        // 判断用户是否已报名
        if (userId != null) {
            String userIdStr = userId.toString();
            boolean hasRegistered = activity.getParticipantIds() != null && 
                                  activity.getParticipantIds().contains(userIdStr);
            vo.setHasRegistered(hasRegistered);
        } else {
            vo.setHasRegistered(false);
        }
        
        return vo;
    }

    /**
     * 将Activity实体转换为ActivityListVO
     */
    private ActivityListVO convertToListVO(CampusActivity activity) {
        ActivityListVO vo = new ActivityListVO();
        BeanUtils.copyProperties(activity, vo);
        
        // 设置描述信息
        vo.setActivityTypeDesc(ActivityConstant.ActivityType.getDescByCode(activity.getActivityType()));
        vo.setActivityStatusDesc(ActivityConstant.ActivityStatus.getDescByCode(activity.getActivityStatus()));
        
        // 获取举办人姓名
        if (activity.getOrganizerId() != null) {
            User organizer = userMapper.selectById(activity.getOrganizerId());
            if (organizer != null) {
                vo.setOrganizerName(organizer.getUsername());
            }
        }
        
        // 判断是否可以报名
        vo.setCanRegister(canRegisterActivity(activity));
        
        return vo;
    }

    /**
     * 判断活动是否可以报名
     */
    private boolean canRegisterActivity(CampusActivity activity) {
        // 检查活动状态
        if (!ActivityConstant.ActivityStatus.REGISTRATION.getCode().equals(activity.getActivityStatus())) {
            return false;
        }
        
        // 检查报名截止时间
        if (activity.getRegistrationDeadline() != null && 
            LocalDateTime.now().isAfter(activity.getRegistrationDeadline())) {
            return false;
        }
        
        // 检查人数限制
        if (activity.getMaxParticipants() > 0 && 
            activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            return false;
        }
        
        return true;
    }

    /**
     * 校验创建活动DTO
     */
    private void validateActivityCreateDTO(ActivityCreateDTO dto) {
        if (dto.getOrganizerId() == null) {
            throw new RuntimeException("举办人ID不能为空");
        }
        if (dto.getActivityName() == null || dto.getActivityName().trim().isEmpty()) {
            throw new RuntimeException("活动名称不能为空");
        }
        if (dto.getActivityTime() == null) {
            throw new RuntimeException("活动时间不能为空");
        }
        if (dto.getActivityTime().isBefore(LocalDateTime.now())) {
            throw new RuntimeException("活动时间不能是过去时间");
        }
        if (dto.getActivityLocation() == null || dto.getActivityLocation().trim().isEmpty()) {
            throw new RuntimeException("活动地点不能为空");
        }
        if (dto.getRegistrationDeadline() != null && 
            dto.getRegistrationDeadline().isAfter(dto.getActivityTime())) {
            throw new RuntimeException("报名截止时间不能晚于活动时间");
        }
    }

    /**
     * 校验编辑活动DTO
     */
    private void validateActivityEditDTO(ActivityEditDTO dto) {
        if (dto.getId() == null) {
            throw new RuntimeException("活动ID不能为空");
        }
        if (dto.getActivityName() == null || dto.getActivityName().trim().isEmpty()) {
            throw new RuntimeException("活动名称不能为空");
        }
        if (dto.getActivityTime() == null) {
            throw new RuntimeException("活动时间不能为空");
        }
        if (dto.getActivityLocation() == null || dto.getActivityLocation().trim().isEmpty()) {
            throw new RuntimeException("活动地点不能为空");
        }
        if (dto.getRegistrationDeadline() != null && 
            dto.getRegistrationDeadline().isAfter(dto.getActivityTime())) {
            throw new RuntimeException("报名截止时间不能晚于活动时间");
        }
    }
} 